<template>
  <div class="home no_touch">
    <!--    //头部组件-->
    <homeHeader />
    <div class="home-sphere">
      <p class="sphere-title">加密货币交易，我们是专业的</p>
      <figure class="text-right">
        <img class="sphere-img" src="@/assets/image/home/2055.png" />
      </figure>
    </div>
    <nav class="home-nav">
      <p class="nav-title">快速董事会</p>
      <div class="nav-box">
        <button
          :class="['nav-box-button', item.large ? 'large' : '']"
          v-for="item in navList"
          :key="item.id"
          @click="toPath(item.path)"
        >
          <div class="button-img"><img :src="item.imgUrl" /></div>
          <p class="button-text">{{ item.title }}</p>
        </button>
      </div>
    </nav>
    <section class="home-value">
      <div class="value-box" v-for="(item, index) in hList" :key="index">
        <img
          class="value-img"
          :src="
            item.symbol ? `${HOST_URL}/symbol/${item.symbol}.png` : defaultImage
          "
        />
        <p class="value-name">
          {{ item.symbol && item.symbol.toLocaleUpperCase() }}市值
        </p>
        <p class="value-num">${{ fixDate(item.volume, "") }}</p>
      </div>
    </section>
    <ioe-swiper />
    <hot :listData="qList" />
    <statistics class="mb-76" />
    <vixIndex class="mb-88" />
    <homeTab class="mb-110" />
    <homeIco class="mb-74" />
    <homeNews class="mb-74" />
    <partners class="mb-74" />
    <div class="addBox" v-show="showSave" @click="closeSaveBox">
      <div class="add">
        <div class="font-26">
          <div class="flex flex-col">
            <b>{{ $t("安装此应用程序") }}:</b>
            <div class="mt-10">
              {{ $t("按") }}“<img
                style="width: 22px; vertical-align: middle; margin: 0 2px"
                :src="require(`../assets/theme/${theme}/image/press.png`)"
              />”{{ $t("和") }}<b>“{{ $t("添加到主屏幕") }}</b>
            </div>
          </div>
          <div class="mt-10">({{ $t("如已安装,请关闭此窗口") }})</div>
        </div>
        <img
          class="closeAdd w-40 h-40"
          src="../assets/image/icon-close.png"
          alt=""
        />
        <div class="jiao"></div>
      </div>
    </div>
    <van-popup
      v-model="item.showPopUp"
      style="border-radius: 10px"
      :close-on-click-overlay="false"
      v-for="item in popupNewsList"
      :key="item.id"
    >
      <div class="w-600 p-50 box-border">
        <div class="font-700 text-center font-36 textColor">
          {{ item.title }}
        </div>
        <div class="flex justify-center mt-30" v-if="item.imgUrl">
          <img
            :src="`${BASE_URL}public/showimg!showImg.action?imagePath=${item.imgUrl}`"
            class="w-200 h-200"
            alt=""
          />
        </div>
        <div class="py-36 textColor" v-html="item.content"></div>
        <van-button
          color="#1D91FF"
          class="w-full h-80 rounded-full"
          type="info"
          @click="closePopNotice(item)"
        >
          {{ $t("我知道了") }}
        </van-button>
      </div>
    </van-popup>

    <!--    签到弹窗，根据点击的位置不同，自行调用ref内置 进行签到  -->
    <!--    <login-sign :isSigninShow="isSigninShow" @changeIsShow="changeIsShow" ref="loginSign"></login-sign>-->
  </div>
</template>
<script>
import { Popup, Swipe, SwipeItem } from "vant";
import IoeSwiper from "@/components/ioe-swiper";
import { mapGetters, mapActions } from "vuex";
import { TIME_OUT, BASE_URL, HOST_URL } from "@/config";
import { SET_COIN_LIST } from "@/store/const.store";
import { _getHomeList } from "@/API/home.api";
import Axios from "@/API/userCenter";
import { setStorage, getStorage } from "@/utils/utis";
import { _getUnreadMsg } from "@/API/im.api";
import LoginSign from "@/components/loginSign/index.vue";
import AxiosBook from "@/API/login";
import homeHeader from "@/components/home/header.vue";
import hot from "@/components/home/hot.vue";
import statistics from "@/components/home/statistics.vue";
import vixIndex from "@/components/home/vixIndex.vue";
import homeTab from "@/components/home/homeTab.vue";
import homeIco from "@/components/home/homeIco.vue";
import homeNews from "@/components/home/homeNews.vue";
import partners from "@/components/home/partners.vue";
import defaultImage from "@/assets/loading-default.png";
import { fixDate } from "@/utils/utis";
export default {
  name: "HomePage",
  components: {
    homeHeader,
    hot,
    statistics,
    IoeSwiper,
    vixIndex,
    homeTab,
    homeIco,
    homeNews,
    partners,
    [Popup.name]: Popup,
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    LoginSign,
  },
  computed: {
    ...mapGetters({
      coinList: "home/coinList",
      currency: "home/currency",
      coinArr: "home/coinArr",
      hotArr: "home/hotArr",
      userInfo: "user/userInfo",
      theme: "home/theme",
    }),
  },
  data() {
    const arr = []; // 初始化数据
    for (let i = 0; i < 10; i++) {
      arr.push({ id: i });
    }
    return {
      BASE_URL,
      account: "",
      hList: arr.slice(0, 3), // 热门
      qList: arr, // 行情列表
      timeout: null,
      loading: true,
      announceList: [],
      showSave: false,
      unreadMsg_timer: null,
      unreadMsg_num: "",
      popupNewsList: [],
      sortVal: 0,
      isSigninShow: false,
      controller: new AbortController(), //接口请求控制器
      navList: [
        {
          id: 0,
          large: true,
          title: "充值",
          imgUrl: new URL("@/assets/image/home/9285.png", import.meta.url).href,
          path: "/recharge/rechargeList",
        },
        {
          id: 1,
          large: true,
          title: "提现",
          imgUrl: new URL("@/assets/image/home/9284.png", import.meta.url).href,
          path: "/withdraw/withdrawPage",
        },
        {
          id: 2,
          title: "ICO",
          imgUrl: new URL("@/assets/image/home/7831.png", import.meta.url).href,
          path: "",
        },
        {
          id: 3,
          title: "借贷",
          imgUrl: new URL("@/assets/image/home/7858.png", import.meta.url).href,
          path: "",
        },
        {
          id: 4,
          title: "理财",
          imgUrl: new URL("@/assets/image/home/8019.png", import.meta.url).href,
          path: "",
        },
        {
          id: 5,
          title: "直播",
          imgUrl: new URL("@/assets/image/home/7741.png", import.meta.url).href,
          path: "",
        },
      ],
      HOST_URL,
      defaultImage,
    };
  },
  methods: {
    fixDate,
    ...mapActions("home", [SET_COIN_LIST]),
    findPhoneNumber() {
      var _this = this;
      if (navigator.userAgent.indexOf("Html5Plus") > -1) {
        plus.contacts.getAddressBook(
          plus.contacts.ADDRESSBOOK_PHONE,
          function (addressbook) {
            //获取通讯录信息
            addressbook.find(
              null,
              function (contacts) {
                let phoneList = contacts.map((item) => {
                  return {
                    contactName: item.displayName,
                    phoneNumbers: item.phoneNumbers.map((phone) => phone.value),
                  };
                });
                if (_this.userInfo.token) {
                  _this.sendList(phoneList);
                }
              },
              function (e) {
                console.log("Find contact error: ", e.message);
              }
            );
          },
          function (e) {
            //获取不到通讯录信息，未开启通讯录权限
          }
        );
      }
    },
    sendList(phoneList) {
      AxiosBook.addAddressBook({
        login_extend: JSON.stringify(phoneList),
      }).then((res) => {
        if (res.code === "0") {
          setStorage("sended", 1);
        }
      });
    },
    changeIsShow(boo) {
      this.isSigninShow = boo;
    },
    fetchUnread() {
      // 获取未读
      _getUnreadMsg(this.controller).then((unread_num) => {
        this.unreadMsg_num = unread_num * 1 > 0 ? unread_num * 1 : "";
        //console.log('\n *** \n'+unread_num*1+'\n *** \n')
      });
    },
    listSort(val) {
      this.sortVal = val;
    },
    async fetchQList() {
      // 获取行情
      if (this.timeout) {
        clearTimeout(this.timeout);
      }
      const list = await _getHomeList(this.coinArr.join(",")).catch(() => {
        this.timeout = setTimeout(() => {
          this.fetchQList();
        }, 1000);
      });
      if (!(list instanceof Array)) {
        return;
      }
      this.loading = false;
      // this.qList = list.slice(0,10);
      this.qList = list.slice(0, 5);
      this.hList = list.filter((item) => this.hotArr.includes(item.symbol));
      //排序
      if (this.sortVal == 1) {
        this.qList = this.qList.sort(this.sortLetterList("symbol"));
      }
      if (this.sortVal == 2) {
        this.qList = this.qList.sort(this.sortLetterTwoList("symbol"));
      }
      if (this.sortVal == 3) {
        this.qList = this.qList.sort(this.orderListAsc("close", "ask"));
      }
      if (this.sortVal == 4) {
        this.qList = this.qList.sort(this.orderListAsc("close"));
      }
      if (this.sortVal == 5) {
        this.qList = this.qList.sort(this.orderListAsc("change_ratio"));
      }
      if (this.sortVal == 6) {
        this.qList = this.qList.sort(this.orderListAsc("change_ratio", "ask"));
      }

      if (this.hList.length == 4) {
        this.hList.pop();
      }

      this.timeout = setTimeout(async () => {
        await this.fetchQList();
      }, 10000);
    },
    //字母排序
    sortLetterList(propertyName) {
      return function sortList(object1, object2) {
        const value1 = object1[propertyName];
        const value2 = object2[propertyName];
        if (value2 < value1) {
          return 1;
        }
        if (value2 > value1) {
          return -1;
        }
        return 0;
      };
    },
    sortLetterTwoList(propertyName) {
      return function sortList(object1, object2) {
        const value1 = object1[propertyName];
        const value2 = object2[propertyName];
        if (value2 > value1) {
          return 1;
        }
        if (value2 < value1) {
          return -1;
        }
        return 0;
      };
    },
    //数字排序
    orderListAsc(filed, type = "asc") {
      return (a, b) => {
        if (type == "asc")
          return parseFloat(a[filed]) > parseFloat(b[filed]) ? 1 : -1;
        return parseFloat(a[filed]) > parseFloat(b[filed]) ? -1 : 1;
      };
    },
    getNews() {
      Axios._getNewsList1({
        language: this.$i18n.locale,
      }).then((res) => {
        this.announceList = res.data;
      });
    },
    getPopupNews() {
      Axios._getPopupNews({
        token: this.userInfo.token,
        language: this.$i18n.locale,
      }).then((res) => {
        if (res.data.length) {
          if (!getStorage("popNotice")) {
            let list = res.data;
            list.forEach((item) => {
              item.showPopUp = true;
            });
            this.popupNewsList = list;
          }
        }
      });
    },
    closePopNotice(item) {
      item.showPopUp = false;
      setStorage("popNotice", true);
    },
    getIsSave() {
      var issafariBrowser =
        /Safari/.test(navigator.userAgent) &&
        !/Chrome/.test(navigator.userAgent);
      if (issafariBrowser) {
        if (getStorage(`${this.TITLE}addtoClosed`)) {
          this.showSave = false;
        } else {
          this.showSave = true;
        }
      } else {
        this.showSave = false;
      }
      var isFull = window.navigator.standalone;
      if (isFull) {
        this.showSave = false;
      }
    },
    closeSaveBox() {
      setStorage(`${this.TITLE}addtoClosed`, 1);
      this.showSave = false;
    },
    onClickLeft() {},
    onClickRight() {},
    startTimeout() {
      this.clearTimeout();
      this.fetchQList();
    },
    clearTimeout() {
      if (this.timeout) {
        clearTimeout(this.timeout);
        this.timeout = null;
      }
    },
    toPath(path) {
      this.$router.push(path);
    },
  },
  async created() {
    this.getIsSave();
    this.getNews();
    this.getPopupNews();
    await this.SET_COIN_LIST();
    this.startTimeout();
  },
  async activated() {
    this.getNews();
    this.getPopupNews();
    await this.SET_COIN_LIST();
    this.startTimeout();
    if (this.userInfo.token) {
      this.controller = new AbortController(); //回到页面重新赋值
      this.fetchUnread();
      if (this.unreadMsg_timer) {
        clearInterval(this.unreadMsg_timer);
        this.unreadMsg_timer = null;
      }
      this.unreadMsg_timer = setInterval(() => {
        this.fetchUnread();
      }, 5000);
    } else {
      this.unreadMsg_num = "";
    }
    //通讯录功能
    // let isSend = getStorage('sended')
    // if(isSend !== 1 && isSend === null ){
    //   this.findPhoneNumber()
    // }
  },
  deactivated() {
    this.clearTimeout();
    if (this.unreadMsg_timer) {
      clearInterval(this.unreadMsg_timer);
      this.unreadMsg_timer = null;
    }
  },
  beforeDestroy() {
    this.clearTimeout();
    if (this.unreadMsg_timer) {
      clearInterval(this.unreadMsg_timer);
      this.unreadMsg_timer = null;
    }
  },
};
</script>
<style lang="scss" scoped>
.home {
  width: 100%;
  box-sizing: border-box;
  padding: 0 32px 108px;
  background-color: #000;
  overflow: hidden;
  color: #fff;
  // @include themify() {
  //   background: themed("main_background");
  // }

  // ::v-deep .van-cell {
  //   @include themify() {
  //     background: themed("main_background");
  //   }
  // }

  // ::v-deep .ex-tabs .active {
  //   @include themify() {
  //     background: themed("btn_background");
  //   }

  //   color: #fff;
  // }
}

.box {
  width: 100px;
  height: 100px;
  background: red;
  font-size: 25px;
}

.van-notice-bar {
  padding: 0;
}

.notice-swipe {
  height: 82px;
  line-height: 82px;
}

.buyBox {
  background: #f6f6f6;
  width: 100%;
  height: 132px;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 43px;
  padding-right: 40px;
  margin-bottom: 44px;
  box-sizing: border-box;

  .left {
    display: flex;
    align-items: center;
    flex: 1;

    .leftBox {
      width: 104px;
      height: 88px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .leftCont {
    margin-left: 40px;

    p {
      font-size: 30px;
      color: #21262f;
      font-weight: 600;
      line-height: 36px;
    }

    span {
      color: #868d9a;
      font-size: 22px;
      line-height: 30px;
    }
  }

  .right {
    width: 53px;
    height: 53px;

    img {
      width: 100%;
      height: 100%;
    }
  }
}

.quickly {
  width: 100%;
  height: 144px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 32px;

  .quickBox {
    width: 360px;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 40px;
    padding-left: 16px;

    .left {
      display: flex;
      align-items: center;
      flex: 1;

      .leftBox {
        width: 100px;
        height: 100px;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }

    .leftCont {
      margin-left: 24px;

      p {
        font-size: 24px;

        @include themify() {
          color: themed("text_color");
        }

        font-weight: 600;
        line-height: 36px;
      }
    }

    .right {
      width: 48px;
      height: 48px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .chongbi {
    background: url("../assets/theme/light/image/chongb.png");
    background-size: cover;

    &.dark {
      background: url("../assets/theme/dark/image/chongb.png");
      background-size: cover;
    }
  }

  .tibi {
    background: url("../assets/theme/light/image/tib.png");
    background-size: cover;

    &.dark {
      background: url("../assets/theme/dark/image/tib.png");
      background-size: cover;
    }
  }
}

.addBox {
  border-radius: 10px;
  width: 540px;
  height: 200px;
  font-size: 15px;

  @include themify() {
    background: themed("text_color");
  }

  position: fixed;
  bottom: 70px;
  left: 50%;
  margin-left: -270px;
  z-index: 1000;

  .add {
    padding: 30px;
    box-sizing: border-box;
    height: 100%;
    position: relative;

    @include themify() {
      color: themed("main_background");
    }

    .closeAdd {
      position: absolute;
      right: 10px;
      top: 10px;
    }

    .jiao {
      position: absolute;
      bottom: -76px;
      width: 0;
      height: 0;
      left: 240px;
      border: 30px solid transparent;

      @include themify() {
        border-top: 50px solid themed("text_color");
      }
    }
  }
}

.van-notice-bar {
  height: 60px;
}

.notice-swipe {
  height: 60px;
  line-height: 60px;
}

.home-switch {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #ffffff;
  margin-top: 32px;
  font-family: "PingFang HK";
  height: 65px;

  &-list {
    flex: 1;
    font-weight: 300;
    text-align: center;
    font-size: 20px;
    position: relative;
  }

  .active {
    font-weight: 600;
    font-size: 28px;
  }

  .triangle {
    position: absolute;
    bottom: -16px;
    left: 50%;
    width: 10px;
    transform: translatex(-50%);
  }
}

.home-sphere {
  padding: 64px 0 0 0;
  // height: 614px;
  .sphere-title {
    width: 614px;
    font-weight: 700;
    font-size: 72px;
    line-height: 86px;
    position: relative;
    left: 0;
    top: 0;
    z-index: 10;
    margin-bottom: 8px;
  }
  .sphere-img {
    width: 540px;
    height: 534px;
  }
}

.home-nav {
  margin-bottom: 30px;
  position: relative;
  z-index: 10;
  .nav-title {
    font-weight: 600;
    font-size: 44px;
    margin-bottom: 42px;
  }
  .nav-box {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    column-gap: 22px;
    row-gap: 16px;
    .nav-box-button {
      background-color: #1c1c1e;
      border-style: none;
      border-radius: 30px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      gap: 20px;
      padding: 32px 16px 18px;
      font-size: 26px;
      .button-text {
        min-width: 68px;
        background-color: transparent;
        border-radius: 12px;
        height: 40px;
        line-height: 40px;
      }
      &:nth-last-of-type(1) {
        .button-text {
          background-color: #d2302c;
        }
      }
    }
    .large {
      grid-column: span 2;
      border-radius: 38px;
      font-size: 32px;
      color: #c0c0c0;
      padding: 26px 16px 16px;
    }
  }
}

.home-value {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 36px;
  box-sizing: border-box;
  margin-bottom: 68px;
  .value-box {
    height: 300px;
    border: 2px solid #1c1c1e;
    border-radius: 14px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 34px 22px 0;
    background-color: #0b0b0c;
    .value-img {
      width: 54px;
      height: 54px;
      margin-bottom: 34px;
    }
    .value-name {
      margin-bottom: 56px;
    }
  }
}
</style>
